import { useState, useEffect } from 'react';
import { Statistic, Space, Select, DatePicker, message } from 'antd';
import styles from './index.module.scss'
import PieChart from './chart/pie'
import BarChart from './chart/stackedBar'
import moment from 'moment';
import dayjs from 'dayjs';
import { costComposition, costTotal, costDetails } from '@/service';
import { useTranslation } from 'react-i18next';

const Option = Select.Option;

export default props => {
    const [type, setType] = useState('month');
    const [compositionObj, setcompositionObj] = useState({});
    const [messageApi, contextHolder] = message.useMessage();
    const [selectedDate, setSelectedDate] = useState(dayjs()); // 默认时间为当前月
    const [year, setYear] = useState('');
    const [month, setMonth] = useState('');
    const [loadingBar, setloadingBar] = useState(true);
    const [processedData, setProcessedData] = useState({});
    const [chartDetail, setchartDetail] = useState([]);
    const { t, i18n } = useTranslation();
    // const chartBarData = {
    //     "type": "year",
    //     "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    //     "series": [
    //         {
    //             "name": "cost",
    //             "data": [1200, 932, 901, 934, 1290, 1330, 1320, 1450, 1600, 1650, 1700, 1800]
    //         },
    //         {
    //             "name": "income",
    //             "data": [820, 932, 901, 934, 1290, 1330, 1320, 1280, 1200, 1250, 1350, 1450]
    //         },
    //         {
    //             "name": "profit",
    //             "data": [400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500]
    //         }
    //     ]

    // };
    // {
    //     "type": "day",
    //         "categories": ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", ..., "23"],
    //             "series": [
    //                 {
    //                     "name": "Operating Income",
    //                     "data": [100, 90, 80, 70, 120, 130, 150, 160, 170, 180, ...]
    //                 },
    //                 {
    //                     "name": "Max Cost",
    //                     "data": [50, 60, 55, 60, 70, 75, 80, 90, 95, 100, ...]
    //                 },
    //                 {
    //                     "name": "Profit",
    //                     "data": [50, 30, 25, 10, 50, 55, 70, 70, 75, 80, ...]
    //                 }
    //             ]
    // }
    // {
    //     "type": "month",
    //         "categories": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", ..., "31"],
    //             "series": [
    //                 {
    //                     "name": "newCount",
    //                     "data": [100, 150, 130, 200, 250, 270, 300, 330, 400, 420, ...]
    //                 },
    //                 {
    //                     "name": "disCount",
    //                     "data": [80, 120, 110, 180, 200, 220, 240, 280, 300, 320, ...]
    //                 },
    //                 {
    //                     "name": "allCount",
    //                     "data": [20, 30, 20, 40, 50, 50, 60, 50, 100, 100, ...]
    //                 },
    //                 {
    //                     "name": "actCount",
    //                     "data": [20, 30, 20, 40, 50, 50, 60, 50, 100, 100, ...]
    //                 }

    //             ]
    // }
    const handleDateChange = (date, dateString) => {
        setSelectedDate(date);
        if (dateString.includes('-')) {
            const [year, month] = dateString.split('-');
            setYear(year);
            setMonth(month);
        } else {
            const year = dateString;
            setYear(year);
            setMonth('');
        }
    };
    const getcostCompositionFn = () => {
        costComposition().then(response => {
            const data = response?.data || {};
            setcompositionObj(data);
        }).catch(e => {
            messageApi.open({
                type: 'error',
                content: e?.message,
            });
        });
    }
    const handleTypeChange = (newType) => {
        setType(newType);
        if (newType === 'month') {
            calculateDates();
            setSelectedDate(dayjs());
        } else if (newType === 'year') {
            const year = dayjs().startOf('year').year();
            setYear(year);
            setMonth('');
            setSelectedDate(dayjs().startOf('year'));
        }
    };
    const calculateDates = () => {
        const year = dayjs().year();
        const month = dayjs().month() + 1;
        setYear(year);
        setMonth(month);
    };
    const processData = (data) => {
        const isMonth = type === 'month';
        const categoriesLength = isMonth ? 31 : 12;
        const categories = Array.from({ length: categoriesLength }, (_, index) =>
            isMonth ? `${index + 1}` : `${index + 1}`
        );
        const cost = Array(categoriesLength).fill(0);
        const income = Array(categoriesLength).fill(0);
        const profit = Array(categoriesLength).fill(0);
        data.forEach((item) => {
            const index = moment(item.statisticalDay).month();
            const day = moment(item.statisticalDay).date();
            const dataIndex = isMonth ? day - 1 : index;
            cost[dataIndex] = item.cost;
            income[dataIndex] = item.income;
            profit[dataIndex] = item.profit;
        });
        return {
            type,
            categories,
            series: [
                { key: 'income', name: t('menu.platform.bar.operatingIncome'), data: income, color: '#EB8F34' },
                { key: 'cost', name: t('menu.platform.bar.maxCost'), data: cost, color: '#306F83' },
                { key: 'profit', name: t('menu.platform.bar.profit'), data: profit, color: '#ccc' },
            ]
        };
    };

    const getCostTotalFn = async (year, month) => {
        let params = {
            year,
            month
        };
        setloadingBar(true);
        const res = await costTotal(params);
        const { code, message, data } = res;
        if (code == 0) {
            setloadingBar(false);
            if (Array.isArray(data) && data.length === 0) {
                setProcessedData({});
            } else {
                const obj = processData(data);
                setProcessedData(obj);
            }
        } else {
            setloadingBar(false);
            messageApi.open({
                type: 'error',
                content: message,
            });
        }
    };
    const getCostDetailsFn = async (year, month) => {
        let params = {
            year,
            month
        };
        const res = await costDetails(params);
        const { code, message, data } = res;
        if (code == 0) {
            if (Array.isArray(data) && data.length === 0) {
                setchartDetail([]);
            } else {
                setchartDetail(data);
            }
            // const datalsit = [{
            //     "statisticalDay": "Amazon Elastic Compute Cloud - Compute",
            //     "cost": 73.23
            // },
            // {
            //     "statisticalDay": "B",
            //     "cost": 73.23
            // },
            // {
            //     "statisticalDay": "C",
            //     "cost": 73.23
            // },
            // //  {
            // //     "statisticalDay": "D",
            // //     "cost": 73.23
            // // },
            // //  {
            // //     "statisticalDay": "E",
            // //     "cost": 73.23
            // // },
            // // {
            // //     "statisticalDay": "E",
            // //     "cost": 73.23
            // // },
            // // {
            // //     "statisticalDay": "E",
            // //     "cost": 73.23
            // // }
            // ]
        } else {
            messageApi.open({
                type: 'error',
                content: message,
            });
        }
    };
    useEffect(() => {
        getcostCompositionFn();
        calculateDates();
    }, [i18n.language]);

    useEffect(() => {
        if (year) {
            getCostTotalFn(year, month || '');
            getCostDetailsFn(year, month || '');
        }
    }, [year, month, i18n.language]);

    return (
        <div className='page-container'>
            <div className={styles.content}>
                <div className={styles.wrapper}>
                    <div className={styles.top}>
                        <div className='custom-title'>{t('menu.platform.title')}</div>
                        <div className={styles.statisBox}>
                            <div className={styles.items}>
                                <Statistic title={<span className={styles.statisticTitle}>{t('menu.platform.business')}</span>} valueRender={() => <span className={styles.moneyValue}>${compositionObj?.income}</span>} />
                                <Statistic title={<span className={styles.statisticTitle}>{t('menu.platform.maximum')}</span>} valueRender={() => <span className={styles.moneyValue}>${compositionObj?.cost}</span>} />
                                <Statistic title={<span className={styles.statisticTitle}>{t('menu.platform.profit')}</span>} valueRender={() => <span className={styles.moneyValue}>${compositionObj?.profit}</span>} precision={2} />
                            </div>
                            <div>
                                <Statistic title={<span className={styles.statisticTitle}>{t('menu.platform.current')}</span>} valueRender={() => <span className={styles.moneytotal}>{compositionObj?.users}</span>} precision={2} />
                            </div>
                        </div>
                    </div>
                    <div className={styles.bottom}>
                        <div className={styles.chartBox}>
                            <div className={styles.time}>
                                <Space>
                                    <Select style={{ width: '100px', marginRight: '20px' }} value={type} onChange={handleTypeChange}>
                                        <Option value="month">{t('menu.platform.month')}</Option>
                                        <Option value="year">{t('menu.platform.year')}</Option>
                                    </Select>
                                    <DatePicker
                                        picker={type}
                                        onChange={handleDateChange}
                                        allowClear={false}
                                        value={selectedDate}
                                        defaultValue={dayjs()}
                                        format={type === 'month' ? 'YYYY-MM' : 'YYYY'}
                                    />
                                </Space>
                            </div>
                            <div className={styles.bottom}>
                                <div className={styles.left}>
                                    <div className={styles.titleBar}>{t('menu.platform.costtotal')}</div>
                                    <BarChart chartBarData={processedData} loading={loadingBar} />
                                </div>
                                <div className={styles.right}>
                                    <div className={styles.titleBar}>{t('menu.platform.costDetails')}</div>
                                    <PieChart data={chartDetail} />
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
            {contextHolder}
        </div>
    )
}
